import { xhrPostJson, xhrGet } from '@/services';
import { useLocation as location } from "@umijs/max";
import { useCallback, useContext, useEffect, useState, useMemo } from 'react';
import {
  onFieldChange,
  onFieldMount,
  onFieldValueChange,
  onFormMount,
  onFormInputChange,
  onFieldInit,
} from '@formily/core';
import { IFieldState } from '@formily/core/lib/types';
import { message, Modal } from 'antd';
import { minus, plus, times, divide, round } from '@ey-utils/utils/numberPrecision';

import { throttle } from 'lodash';

import { isArrayField, isVoidField } from '@formily/core';

import { Field, Form } from '@formily/core/esm/models';
import { commomStateUse, dealProps, setDefaultUser, setSelectInitialValue } from './util';
import GlobalContext from '@/context';

import { getLocal } from '@ey-utils/utils/utils';
import { useVisible } from '@/biz-components/modals/hooks';
import { toArray } from '@/biz-components/_common/util';
import AsyncConfirm from "@/biz-components/async-confirm";
import _ from 'lodash';
import { MessageContent } from './messageContent';


const NOTICE_EVENT_NAME = 'notice';
const BILL_EVENT_NAME = 'BILL_NOTICE';

const REFRESH_VOUCHER = 'REFRESH_VOUCHER';

const TODO_APPROVE_EVENT = 'TODO_APPROVE_EVENT';

const CustomEvent = require('custom-event');

export const useLocation = () => {
  const { search } = location();
  const query: { [key: string]: any } = search
      .substring(1)
      .split("&")
      .reduce((pre, cur) => {
        const [key, value] = cur.split("=");
        pre[key] = value;
        return pre;
      }, {});
  return { query: query };
};

export default useLocation;


export interface ExtraParams {
  prcsInstId: string;
  taskId: string;
}

export interface BillParams {
  code: string | null;
  needFooter: boolean;
  query: any;
  pageCode: string;
  taskId: string;
  pageType: string;
  type: string;
  billType?: string;
  prcsState?: string;
  isComponent?: boolean;
}

export const useEmit = (emitEvent: string) => {
  const { emitter } = useContext(GlobalContext);

  return (params?: any) => {
    if (emitter) {
      emitter.emit(emitEvent, params);
    }
  };
};

export const useReceiver = (emitEvent: string, cb: (...arg: any) => void, timer?: number) => {
  const { emitter } = useContext(GlobalContext);

  useEffect(() => {
    const callback = timer ? throttle(cb, timer) : cb;

    emitter?.on(emitEvent, callback);
    return () => {
      emitter?.off(emitEvent, () => {});
    };
  }, [emitEvent]);
};

export const useNoticeVoucherEvent = () => {
  const dispatch = useEmit(REFRESH_VOUCHER);

  return (code: any) => {
    if (code) {
      dispatch({ code });
    }
  };
};

export const emitTodoEvent = (
  form: any,
  isChange: boolean,
  checkFunc?: (params?: any) => Promise<void>,
) => {
  document.dispatchEvent(
    new CustomEvent(TODO_APPROVE_EVENT, {
      detail: {
        form,
        isChange,
        checkFunc,
      },
    }),
  );
};

export const useReceiverTodoEvent = (cb: (...arg: any) => void) => {
  useEffect(() => {
    document.addEventListener(TODO_APPROVE_EVENT, (e: any) => {
      cb(e.detail.form, e.detail.isChange, e.detail.checkFunc);
    });

    return () => {
      document.removeEventListener(TODO_APPROVE_EVENT, () => {});
    };
  }, []);
};

export const todoApproveCheck = (checkFunc?: (params?: any) => Promise<void>) => {
  onFormMount((form) => {
    emitTodoEvent(form, false, checkFunc?.bind(null, form));
  });

  onFormInputChange((form) => {
    emitTodoEvent(form, true);
  });
};

interface I18nBillName {
  zh_CN: string;
  en_US: string;
}
// 特殊变量存储值

export const useBillParams = (props?: any): BillParams => {
  const { query }: any = props?.businessNo
    ? {
        query: {
          businessNo: props?.businessNo,
          pageCode: props?.businessType,
          taskId: props?.taskId,
          btn: props?.btn,
          pageType: props?.pageType,
          type: props?.type,
          prcsState: props?.prcsState,
        },
      }
    : useLocation();
  const [code, setCode] = useState<string | null>(null);

  useEffect(() => {
    const { businessNo, code } = query || {};
    if (businessNo) {
      setCode(businessNo);
    }

    if (code) {
      setCode(code);
    }
  }, [query]);
  // 通过浏览器传参或者通过props传参来配置needFooter，否则用btn来判断
  const needFooter = props?.hasOwnProperty('needFooter')
      ? props?.needFooter
      : (query?.needFooter === 'false' ? false : !!(props?.btn ?? true));

  return {
    code,
    isComponent: props?.isComponent,
    needFooter,
    query,
    pageCode: query?.pageCode,
    taskId: query?.taskId,
    pageType: query?.pageType,
    billType: query?.billType,
    type: query?.type,
    prcsState: query?.prcsState,
  };
};

export const useNoticeEvent = (
  eventTarget: ({ form, noticeParams }: { form: Form; noticeParams: any }) => void,
  form: Form,
) => {
  useEffect(() => {
    document.addEventListener(NOTICE_EVENT_NAME, (e: any) => {
      eventTarget?.({ form, noticeParams: e.detail });
    });

    return () => {
      document.removeEventListener(NOTICE_EVENT_NAME, () => {});
    };
  }, [eventTarget]);
};

export const useAttachmentFieldMount = (filed: string) => {
  const attachmentMount = useCallback(() => {
    if (!filed) return;

    onFieldMount(filed, (_, form) => {
      form.setFieldState(filed, (state) => {
        state.validator = {
          // @ts-ignore
          ...state.validator,
        };
      });
    });
  }, [filed]);

  return [attachmentMount];
};

export const useFormMount = () => {
  const [form, setForm] = useState<any>(null);

  const mount = useCallback(() => {
    onFormMount((newForm) => {
      setForm(newForm);
    });
  }, []);

  return [form, mount];
};

/**
 * 统计表格求和 赋值给外层
 * @param form
 * @param key 表格名称
 * @param target 需要赋值的字段
 * @param value 表格中计算和的属性
 */
export const totalHooks = (
  form: any,
  key = 'claimDetail',
  target = 'totalAmount',
  value = 'claimedAmount',
) => {
  form.setFieldState(target, (state: IFieldState) => {
    const text = form.getFieldState(key)?.value || [];
    try {
      state.value = text.reduce((total: number, cur: any) => {
        return plus(total, cur && cur[value] ? cur[value] : 0);
        // return Number(Number(cur && cur[value] ? cur[value] : 0) + Number(total || 0)).toFixed(2)
      }, 0);
    } catch (e) {
      console.error(`求和方法出错，totalHooks ${e}`);
    }
  });
};



/**
 * @description 公司初次改动时，使对应数据
 * @param { setDefaultUserKey, setSelectInitialValueKey }  人员，部门对应 key
 * @param others 其他 hook
 */
export const initialCompanyAndDeptValue = (
  params: any = {},
  others?: (form: Form, st?: any) => any,
  noNeedModify?: boolean,
) => {
  const {
    onFieldChangeKey = 'companyCode',
    setDefaultUserKey = 'loaner',
    setSelectInitialValueKey = 'deptCode',
  } = params;

  setTargetValuesWithKey(['companyCodeName', 'deptName']);
  onFieldChange(onFieldChangeKey, (state, form) => {
    if (noNeedModify) {
      others && others(form, state);
    }
    // @ts-ignore
    if (state.modified) {
      setDefaultUser(form, setDefaultUserKey);
      setSelectInitialValue(form, setSelectInitialValueKey);
      others && others(form, state);
    }
  });
  // 增加对部门名称的赋值
  onFieldValueChange(setSelectInitialValueKey, (state, form) => {
    if (state.modified) {
      form.getFieldState(
        'deptName',
        (st) => (st.value = state?.query(`.deptCode`)?.getIn()?.inputValues[2]?.name),
      );
      others && others(form);
    }
  });
};



export type apiType = {
  url: string;
  method: 'POST' | 'GET';
  params: any;
};
/**
 *
 * @param api
 * @returns 根据 api 配置返回对应请求方法
 */
export const useApiFunc = (api: apiType) => {
  const { method, url, params } = api;
  const rqFunc = useMemo(() => {
    return method.toUpperCase() === 'POST'
      ? (exParams: any) =>
          xhrPostJson(url, {
            ...params,
            ...exParams,
          })
      : (exParams: any) => xhrGet(url, { ...params, ...exParams });
  }, [JSON.stringify(api)]);
  return [rqFunc];
};

/**
 *
 * @param changeKeys
 * @description 注册供应商合同,采购订单，银行账号关联
 */
const defaultKeys_contract = [
  'cntrctName',
  'cntrctOptor',
  'cntrctOpDpt',
  'cntrctAmount',
  'cntrctOwner',
  'cntrctSplr',
];
const defaultKeys_bank = ['bankAcctName', 'bankName', 'bankCode'];
export const splrWtihRelations = (
  initialKeys_contract = defaultKeys_contract,
  initialKeys_bank = defaultKeys_bank,
) => {};

/**
 *
 * @param keys 数组，或者单个字符串
 * @param index 获取 onChange 参数，默认为第二个（识组件自行适配）
 * @description targetKey为目标字段，targetKeyMap为获取 json 的取值字段，均在组件属性中配置
 */
export const setTargetValuesWithKey = (keys: string[] | string, index: number = 1) => {
  console.log('setTargetValuesWithKey', keys)
  if (Array.isArray(keys)) {
    keys.forEach((k) => dealTargetValuesWithKey(k, index));
  } else {
    dealTargetValuesWithKey(keys, index);
  }
};

const dealTargetValuesWithKey = (key: string, index: number = 1) => {
  console.log('dealTargetValuesWithKey', key)
  onFieldValueChange(key, (st, form) => {
    console.log('???', st.modified);
    // 未被修改不做任何操作
    if (!st.modified) return;
    // 是否需要清空标记
    const noClear = !!st.value;
    const ut = dealProps(form);
    // 默认设置取 onChange第二个参数,获取 json；
    const args = commomStateUse.getChangedValues(st);
    const cn = args[index] || {};
    const targetKey = st.componentProps?.targetKey;
    const targetKeyMap = st.componentProps?.targetKeyMap || {};

    if (Array.isArray(targetKey)) {
      targetKey.forEach((k) => {
        const mapKey = targetKeyMap[k] || k;
        ut(k, 'value', noClear ? cn[mapKey] || '' : '');
      });
    }
  });
};

/**
 *
 * @param keys 数组，或者单个字符串
 * @param index 获取 onChange 参数，默认为第二个（识组件自行适配）
 * @description targetKey为目标字段，targetKeyMap为获取 json 的取值字段，均在组件属性中配置
 */
export const setTargetValuesWithArrayKey = (keys: string[] | string, index: number = 1) => {
  if (Array.isArray(keys)) {
    keys.forEach((k) => dealTargetValuesWithArrayKey(k, index));
  } else {
    dealTargetValuesWithArrayKey(keys, index);
  }
};

export const dealTargetValuesWithArrayKey = (key: string, index: number = 1) => {
  onFieldValueChange(key, (st, form) => {
    // 未被修改不做任何操作
    if (!st.modified) return;
    // 是否需要清空标记
    const noClear = !!st.value;

    // 默认设置取 onChange第二个参数,获取 json；
    const args = commomStateUse.getChangedValues(st);
    const cn = args[index] || {};
    const targetKey = st.componentProps?.targetKey;
    const targetKeyMap = st.componentProps?.targetKeyMap || {};

    if (Array.isArray(targetKey)) {
      targetKey.forEach((k) => {
        const mapKey = targetKeyMap[k] || k;
        st.query(`.${k}`).take((state) => {
          state.value = noClear ? cn[mapKey] || '' : '';
        });
      });
    }
  });
};

export const validateAmount = (form: Form, target: string, values: Array<string>) => {
  const amount = values.reduce(
    (prev, curr) => plus(prev || '0', form.values[curr] || '0'),
    form.values[values[0]],
  );
  if (Number(amount) === Number(form?.values[target] || '0')) {
    return true;
  }
  const diffAmount = minus(form?.values[target], amount);
  message.warn(`电汇金额 + 资产抵账金额 + 票据金额 不等于 需付款金额: 差额 ${diffAmount}`);
  return false;
};


export const validateFieldAmount = (
  form: Form,
  target: string,
  values: Array<string>,
  rule: string,
  i18n: string,
) => {};

export const fieldVisible = (
  form: Form,
  when: boolean,
  fulfill: string[],
  otherwise: string[],
  noClear?: boolean,
) => {
  const resetValue = (state: any, visible: boolean, field: string) => {
    if (!visible && !isVoidField(state) && !noClear) {
      const val = toArray(state.value);
      state.reset({ forceClear: true });
      if (isArrayField(state)) {
        form.setValuesIn(field, []);
        val.forEach((_) => {
          state.remove(0);
        });
      } else {
        form.setValuesIn(field, undefined);
      }
    }

    state.visible = visible;
  };

  fulfill.forEach((key) => {
    form.setFieldState(key, (state) => {
      resetValue(state, when, key);
    });
  });

  otherwise.forEach((key) => {
    form.setFieldState(key, (state) => {
      resetValue(state, !when, key);
    });
  });
};

export const arrayFieldChangeSum = (
  changFields: string[],
  valueField: string,
  targetMap: Object,
  isModified?: boolean,
) => {
  const sum = (form: Form) => {
    const data = toArray(form.getValuesIn(valueField));

    Object.keys(targetMap).forEach((key) => {
      const sumValue = data.reduce((acc: number, cur: any) => {
        return plus(acc, cur[key] || 0);
      }, 0);

      form.setValuesIn(targetMap[key], sumValue);
    });
  };

  changFields.forEach((key) => {
    onFieldChange(key, (field, form) => {
      if (field.modified || isModified) {
        sum(form);
      }
    });
  });
};

export const getKey = () => {
  let time = new Date().valueOf();
  return time;
};

export const madeOrgChange = () => {
  orgChange({
    user: 'madeUser',
    userName: 'madeUserName',
    company: 'companyCode',
    companyName: 'companyName',
    department: 'deptCode',
    departmentName: 'deptName',
  });
};

export const rbrsOrgChange = () => {
  orgChange({
    user: 'rbrsUser',
    userName: 'rbrsUserName',
    company: 'rbrsUserCo',
    companyName: 'rbrsUserCoName',
    department: 'rbrsUserDeptCode',
    departmentName: 'rbrsUserDeptName',
  });
};

interface OrgFieldChange {
  user: string; //
  userName: string; //
  company: string; //
  companyName: string; //
  department: string;
  departmentName: string;
}

export const orgChange = (org: OrgFieldChange) => {
  const { user, userName, company, companyName, department, departmentName } = org || {};

  setTargetValuesWithKey([user, departmentName, companyName]);

  onFieldInit(departmentName, (field) => {
    field.componentProps = {
      columnRenderType: true,
      needValue: false,
      deps: [],
      ...field.componentProps,
      valueTemplateKey: 'name',
      labelTemplateKey: 'name',
      targetKey: [department],
      _disabled: field.disabled,
      targetKeyMap: {
        [department]: 'code',
      },
    };
  });

  const departmentProps = (form: Form) => {
    const companyCode = form.getValuesIn(company);
    const userCode = form.getValuesIn(user);
    form.setFieldState(departmentName, (state: any) => {
      const disabled = !(companyCode && userCode);

      state.disabled = state.componentProps._disabled || disabled;

      state.componentProps.disabled = state.componentProps._disabled || disabled;

      state.componentProps.initDefaultValue = true;
      state.componentProps.api =
        companyCode && userCode
          ? {
              url: '/sym/org/findDeptByCompanyAndUser',
              type: 'GET',
              params: {
                parentCode: companyCode,
                userCode: userCode,
              },
            }
          : {};
    });
  };

  const companyProps = (form: Form) => {
    form.setFieldState(companyName, (state: any) => {
      const userCode = form.getValuesIn(user);
      const disabled = !userCode;

      state.disabled = state.componentProps._disabled || disabled;
      state.componentProps.disabled = state.componentProps._disabled || disabled;
      state.componentProps.initDefaultValue = true;
      state.componentProps.api = userCode
        ? {
            url: '/sym/company/getByUserCode',
            type: 'GET',
            params: {
              userCode: userCode,
            },
          }
        : {};
    });
  };

  onFieldInit(companyName, (field) => {
    field.componentProps = {
      columnRenderType: true,
      needValue: false,
      deps: [],
      ...field.componentProps,
      valueTemplateKey: 'name',
      labelTemplateKey: 'name',
      targetKey: [company],
      _disabled: field.disabled,
      targetKeyMap: {
        [company]: 'code',
      },
    };
  });

  onFieldChange(companyName, ['value'], (field: any, form: any) => {
    window.requestAnimationFrame(() => {
      departmentProps(form);
      if (field.modified) {
        form.setValuesIn(department, '');
        form.setValuesIn(departmentName, '');
      }
    });
  });

  onFieldInit(user, (field, form) => {
    field.componentProps = {
      ...field.componentProps,
      columns: [
        {
          dataIndex: 'code',
          title: 'select.table.user.column.code',
        },
        {
          dataIndex: 'name',
          title: 'select.table.user.column.name',
        },
        {
          dataIndex: 'userOrgs',
          title: 'select.table.user.column.org',
        },
      ],
      api: {
        method: 'post',
        params: {},
        url: '/sym/user/pageByCodeOrName',
      },
      enabledExactQuery: true,
      exactQueryParamsArray: false,
      optionLabelProp: 'label',
      exactQueryParamKey: ['value'],
      targetKey: [userName],
      targetKeyMap: {
        [userName]: 'name',
      },
    };
  });

  onFieldChange(user, ['value'], (field: any, form: any) => {
    window.requestAnimationFrame(() => {
      companyProps(form);
      if (field.modified) {
        form.setValuesIn(company, '');
        form.setValuesIn(companyName, '');
      }
    });
  });
};


export const changePriorItemsCode = () => {
  onFieldChange("priorItems.*.code", (st: any, form) => {
    if(st.modified && st.value) {
      const pAddress = st.path.parent().toString();
      // 处理事前申请单号去重;
      const { inputValues } = st;
      const { priorItems } = form?.values;
      let { claimAmt, applyDescr } = inputValues?.[1] || {};
      const codes = priorItems?.filter(it => {
        return it.code === st.value;
      }) || [];
      if (codes?.length && codes?.length > 1) {
        st.value = '';
        claimAmt = '';
        applyDescr = '';
        message.warn('这个事前申请已经选择过了, 请选择其他单号');
      }
      if (inputValues.length > 0) {
        form.setValuesIn(`${pAddress}.[claimAmt, applyDescr]`, [claimAmt, applyDescr])
      }
    }
  });
}

// 收款信息
export const initPymtItems = (form: any, code: string) => {
  console.log('initPymtItems', code)

  form.setFieldState('pymtItems.*.bankAcct', (st) => {
    // const hasCode = !!code
    // st.componentProps.initDefaultValue = hasCode;
    st.componentProps.api = {
      ...st.componentProps.api,
      "type": "post",
      "url": "/asm/bankAcct/list",
      "params": {
        pageCode: 'BankAcct_List',
        code,
      }
    }
  });
}
export const changePymtItemsCode = () => {
  onFieldChange("pymtItems.*.bankAcct", (st: any, form) => {
    console.log("onFieldChange pymtItems.*.bankAcct", st.inputValues);
    const { inputValues } = st;
    if (inputValues.length > 0 && st.value) {
      console.log("st.parent 4", st.parent, inputValues);
      // 付款方式pymtType 付款类型pymtCtgry  收款方类型payeeType 固定取init的值，不需要更改
      form.setValuesIn("pymtItems.0.[" +
          "bankName, " + // 开户行
          "bank," + // 行号
          "bankAcctName," + // 行号
          "ieAmt" + //  支付金额
          // "payer," + // 付款方 取记账组织
          // "payerName" + // 付款方 取记账组织
          // "payee" + // 收款方
          // "payeeName" + // 收款方
          "]",
          [
            inputValues[1].bankName,
            inputValues[1].bankNo,
            inputValues[1].bankAcctName,
            form.values.ieBaseAmt || 0,
            // form?.values?.acctCo,
            // form?.values?.acctCoName,
            // form?.values?.payee,
            // form?.values?.payeeName
          ])
    }
    if(!st.value) {
      form.setValuesIn("pymtItems.0.[" +
          "bankName, " + // 开户行
          "bank," + // 行号
          "bankAcctName," + // 行号
          "ieAmt" + //  支付金额
          // "payer," + // 付款方 取记账组织
          // "payerName" + // 付款方 取记账组织
          // "payee" + // 收款方
          // "payeeName" + // 收款方
          "]", //
          [])
    }
  });
}

export const initApplicantBankAcct = () => {
  setTargetValuesWithKey(['bankAcctCode']);
  onFormMount((form) => {
    const code = form.getValuesIn('madeUser');
    form.setFieldState('bankAcctCode', (state) => {
      state.componentProps.initDefaultValue = true;
      state.componentProps.targetKey = ['bankAcctName', 'bankCode', 'bankName'];
      state.componentProps.targetKeyMap = {
        bankCode: 'bankNo',
      };
      state.componentProps.initDefaultValue = true;
      state.componentProps.api = {
        url: '/asm/bankAcct/list',
        type: 'post',
        params: {
          code: code,
          pageCode: 'BankAcct_List',
          bankAcctType: 'Supplier',
        },
      };
    });
  });
};

export const billPaymentMethodChange = (paymentMethod?: string) => {
  const paymentMethodField = paymentMethod || 'paymentMethod';
  onFieldChange(paymentMethodField, (fie: any, form: any) => {
    switch (fie.value) {
      case 'URI':
        form.setFieldState('*(bankAcctCode,bankAcctName,bankCode,bankName)', (st: any) => {
          st.visible = false;
        });
        form.setFieldState('*(uri)', (st: any) => {
          st.visible = true;
        });
        break;
      case 'CASH':
        form.setFieldState('*(bankAcctCode,bankAcctName,bankCode,bankName,uri)', (st: any) => {
          st.visible = false;
        });
        break;
      case 'FREE': {
        form.setFieldState('*(bankAcctCode,bankAcctName,bankCode,bankName)', (st: any) => {
          st.visible = true;
        });
        form.setFieldState('*(bankAcctCode)', (st: any) => {
          st.componentProps.componentType = 'Input';
        });

        form.setFieldState('*(bankAcctName,bankCode,bankName)', (st: any) => {
          st.disabled = false;
          st.componentProps.disabled = false;
        });

        form.setFieldState('*(uri)', (st: any) => {
          st.visible = false;
        });
        break;
      }
      case 'BANK':
        form.setFieldState('*(bankAcctCode)', (st: any) => {
          st.componentProps.componentType = '';
        });
        form.setFieldState('*(bankAcctName,bankCode,bankName)', (st: any) => {
          st.disabled = true;
          st.componentProps.disabled = true;
        });
        form.setFieldState('*(bankAcctCode,bankAcctName,bankCode,bankName)', (st: any) => {
          st.visible = true;
        });
        form.setFieldState('*(uri)', (st: any) => {
          st.visible = false;
        });
        break;
      default:
        form.setFieldState('*(uri,bankAcctCode,bankAcctName,bankCode,bankName)', (st: any) => {
          st.visible = false;
        });
        break;
    }

    if (fie.modified) {
      form.setFieldState('*(uri,bankAcctCode,bankAcctName,bankCode,bankName)', (st: any) => {
        st.value = '';
      });
    }
  });
};

export const initBillPaymentMethod = (scene: string, paymentMethod?: string) => {
  const paymentMethodField = paymentMethod || 'paymentMethod';

  setTargetValuesWithKey(paymentMethodField);

  onFieldInit(paymentMethodField, (field) => {
    xhrPostJson('asm/formType/detail', {
      code: scene,
      pageCode: 'BillTypeTree_CU',
    }).then((res) => {
      const { paymentMethodName, paymentMethod } = res.result || {};
      const paymentMethodNameArr = paymentMethodName?.split(',') || [];
      field.componentProps.api = {};
      field.componentProps.data = paymentMethod.map((val, index) => {
        return {
          code: val,
          name: paymentMethodNameArr[index],
        };
      });
      field.componentProps.initDefaultValue = true;
    });
  });

  billPaymentMethodChange(paymentMethodField);
};

/**
 *
 * @param groupKey submodal主表上key值
 * @param targetKey 行上需要设置最大值限制的key
 * @param maxKey 行上最大值的取值目标
 * @param msgs 提示语句 [最小, 最大, 必填]
 * @description 针对行项目金额 0-max 限制配置。只在初始化进行设置一次。
 */
export const useSubmodalMaxCheck = (
  groupKey: string,
  targetKey: string,
  maxKey: string,
  msgs: any[] = [],
) => {
  onFieldChange(`${groupKey}.*.${targetKey}`, (field, form) => {
    const index: any = field.address.segments[4];
    // @ts-ignore
    if (field?.setHH === true) return;
    setValidatorOfAmount(groupKey, targetKey, maxKey, index, form, msgs);
  });
};

// 设置校验
const setValidatorOfAmount = (
  groupKey: string,
  targetKey: string,
  maxKey: string,
  index: any,
  form: any,
  msgs: string[],
) => {
  const groupItem = form.getValuesIn(groupKey);
  const opValue: any = groupItem[index];
  const maxValue = opValue?.[maxKey];
  setTimeout(() => {
    form.getFieldState(`${groupKey}.${index}.${targetKey}`, (amt: any) => {
      amt.setHH = true;
      amt.validator = [
        { min: 0, message: msgs?.[0] || '本次交回金额不能小于0' },
        { max: +maxValue, message: msgs?.[1] || '本次交回金额不能大于未交回金额' },
        {
          required: true,
          message: msgs?.[2] || '请填写本次交回金额',
        },
      ];
    });
  }, 500);
};

/**
 * 初始化油费是否显示
 * @param form
 */
export const handleGas = (form) => {
  form.setFieldState('gasInfo', st => {
    st.visible = form?.values?.acctItems?.filter(it => {
      return it.tag === 'JYF' || it.acctType === 'DS_JYF' || it.acctType === "CL_JYF" || it.tag === 'ZF';
    })?.length > 0;
  });
};
// 设置申请人公司
export const setEditApplyCo = (form) => {
  form.setFieldState('applyCo', (st) => {
    st.componentProps.api = {
        ...st.componentProps.api,
        params: {
            ...st.componentProps.params,
            userCode: form.getValuesIn('aplyUser')
        }
    }
});
}
/**
 * YAD-275
 【分摊校验】提交时针对分摊明细进行预算相关与记账相关的校验
 涉及单据
 报销单：差旅、招待、会议、对私
 对公报账：对公发票入账支付单，在建工程发票入账支付单，平台服务费冲账单，对公发票入账(销售折扣折让处理)，对公发票入账-收票核销单
 * @param item
 * 若 记账金额（alloctnAmt） 不为 0 时，需要增加如下校验：
 成本中心（costCtr）不能为空
 若 预算科目（bdgtAcct）不为空时
 项目（proj）或 预算部门（bdgtDept）两者 不能全为 空
 * @param noNeedCostCtr 是否需要校验成本中心为空，默认需要校验
 * @param noNeedBdgtAcct 是否需要校验预算科目,默认需要校验
 */

export const checkBdgt = (item: any, noNeedCostCtr: boolean = false, noNeedBdgtAcct: boolean = false) => {
  let flag = 0;
  if (item && item?.alloctnAmt) {
    if (!item.costCtr && !noNeedCostCtr) {
      message.error(`${item.deptName}错误，成本中心不能为空`);
      flag = 1;
    }
    // 若 预算科目（bdgtAcct）不为空时
    // 项目（proj）或 预算部门（bdgtDept）两者 不能全为 空
    if (item.bdgtAcct && !noNeedBdgtAcct) {
      if (!item.proj && !item.bdgtDept) {
        message.error(`${item.deptName}错误，若 预算科目不为空时, 项目或 预算部门两者 不能全为 空`);
        flag = 2;
      }
    }
  }
  return flag === 0;
};




/*
* 事前申请批量删除
* */

export const batchPriorItemsDelete = (e: any, payload: any) => {
  const { field } = payload;
  return (payload.field.value = field.value.filter((item: any) => {
    return !item.selections;
  }));
}

// format submit data
export const formatFormDataCommon = (formValues: any) => {
  const {alloctnItems = [], acctItems, ocpdItems, pymtItems, crncy } = formValues;
  let newPcpdItems = [];
  let newPymtItems = []
  // 设置付款信息附加字段
  console.log('设置付款信息附加字段')
  if(pymtItems.length > 0) {
    newPymtItems = pymtItems.map(item => {
      return {
        ...item,
        crncy
      }
    })
  }
  // 核销备用金时，若不填写核销金额 或 核销金额为 0 删除当前记录
  if(ocpdItems?.length) {
    newPcpdItems = ocpdItems.filter(item => {
      const { claimAmt } = item;
      return claimAmt && claimAmt !== 0
    })
  }
  return {
    ...formValues,
    ocpdItems: newPcpdItems,
    pymtItems: newPymtItems,
  };
};

export const useBillBreadcrumbEvent = (billName: I18nBillName, type?: string) => {
  useMemo(() => {
    if (type) {
      useBillBreadcrumbName(type).then((res) => {
        const { result } = res || {};
        const { name } = result || {};

        document.dispatchEvent(
          new CustomEvent(BILL_EVENT_NAME, {
            detail: {
              billName: name || billName,
            },
          }),
        );
      });
    }
  }, [type]);

  useEffect(() => {
    const local = getLocal();
    document.dispatchEvent(
      new CustomEvent(BILL_EVENT_NAME, {
        detail: {
          billName: billName?.[local] || billName,
        },
      }),
    );
    return () => {
      document.dispatchEvent(
        new CustomEvent(BILL_EVENT_NAME, {
          detail: {
            billName: '',
          },
        }),
      );
    };
  }, [JSON.stringify(billName)]);
};
